package flc.ast.fragment.edit;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.stark.imgedit.ImgEditActivity;
import com.stark.imgedit.ModuleConfig;
import com.stark.imgedit.adapter.MosaicImgAdapter;
import com.stark.imgedit.utils.Matrix3;
import com.stark.imgedit.view.MosaicPaintView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import flc.ast.BaseEditFragment;
import flc.ast.R;
import flc.ast.adapter.MosaicAdapter;
import flc.ast.bean.MyMosaicBean;
import flc.ast.databinding.FragmentMosaicBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.AssetUtil;
import stark.common.basic.utils.RxUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MosaicFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MosaicFragment extends BaseEditFragment<FragmentMosaicBinding> {

    public static final int INDEX = ModuleConfig.INDEX_MOSAIC;
    private static final String ASSET_MOSAIC_DIR = "mosaic";

    private MosaicPaintView mPaintView;
    private MosaicAdapter mAdapter;
    private int oldPosition;

    private int paintWidth = 5;

    public static MosaicFragment newInstance() {
        MosaicFragment fragment = new MosaicFragment();
        return fragment;
    }

    @Override
    public void onShow() {
        mImgEditActivity.mode = ImgEditActivity.MODE_MOSAIC;
        mImgEditActivity.mImgView.setImageBitmap(mImgEditActivity.getMainBit());
        mPaintView.setVisibility(View.VISIBLE);

        mPaintView.setWidth(paintWidth);
        mPaintView.setEraser(false);
        if (mAdapter != null) {
            oldPosition = 0;
            mAdapter.getItem(0).setSelect(true);
            String path = mAdapter.getItem(0).getPath();
            setMosaicBitmap(path);
        }
    }

    @Override
    public void backToMain() {
        mImgEditActivity.mode = ImgEditActivity.MODE_NONE;
        mImgEditActivity.mImgView.setVisibility(View.VISIBLE);
        mPaintView.setVisibility(View.GONE);
        mPaintView.reset();
        mImgEditActivity.showFunc();
    }

    @Override
    protected int onCreate() {
        return R.layout.fragment_mosaic;
    }

    @Override
    protected void initView() {
        mPaintView = mImgEditActivity.mMosaicPaintView;

        mDataBinding.ivCancel.setSelected(true);
        mDataBinding.ivApply.setOnClickListener(this);
        onShow();

        //设置画笔大小
        mDataBinding.sbSize.setMax(50);
        mDataBinding.sbSize.setProgress(5);
        mDataBinding.sbSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //画笔擦大小
                paintWidth = 5 + i * 2;
                mImgEditActivity.mMosaicPaintView.setWidth(paintWidth);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivCancel://取消
                backToMain();
                break;
            case R.id.ivApply://确定
                applyMosaicImage();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        mAdapter.getItem(oldPosition).setSelect(false);
        oldPosition = position;
        mAdapter.getItem(position).setSelect(true);
        mAdapter.notifyDataSetChanged();
        setMosaicBitmap(mAdapter.getItem(position).getPath());
    }

    @Override
    protected void initData() {//layout manager
        mDataBinding.rvMosaic.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        mAdapter = new MosaicAdapter();
        mAdapter.setOnItemClickListener(this);
        mAdapter.setList(loadDatas());
        mDataBinding.rvMosaic.setAdapter(mAdapter);
    }

    private List<MyMosaicBean> loadDatas() {
        List<String> listPath = AssetUtil.getFilePathsWithAssetPrefix(getContext(), ASSET_MOSAIC_DIR);
        List<MyMosaicBean> list = new ArrayList<>();
        for (String s : listPath) {
            list.add(new MyMosaicBean(s, false));
        }
        list.get(0).setSelect(true);
        return list;
    }

    public void applyMosaicImage() {
        showDialog(getString(com.stark.common.res.R.string.handling));
        RxUtil.create(new RxUtil.Callback<Bitmap>() {
            @Override
            public void doBackground(ObservableEmitter<Bitmap> emitter) {
                Matrix touchMatrix = mImgEditActivity.mImgView.getImageViewMatrix();

                Bitmap retBitmap = Bitmap.createBitmap(mImgEditActivity.getMainBit()).copy(
                        Bitmap.Config.ARGB_8888, true);
                Canvas canvas = new Canvas(retBitmap);

                float[] data = new float[9];
                touchMatrix.getValues(data);// 底部图片变化记录矩阵原始数据
                Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
                Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
                Matrix m = new Matrix();
                m.setValues(inverseMatrix.getValues());

                float[] f = new float[9];
                m.getValues(f);
                int dx = (int) f[Matrix.MTRANS_X];
                int dy = (int) f[Matrix.MTRANS_Y];
                float scale_x = f[Matrix.MSCALE_X];
                float scale_y = f[Matrix.MSCALE_Y];
                canvas.save();
                canvas.translate(dx, dy);
                canvas.scale(scale_x, scale_y);

                if (mPaintView.getPaintBit() != null) {
                    canvas.drawBitmap(mPaintView.getPaintBit(), 0, 0, null);
                }
                canvas.restore();

                emitter.onNext(retBitmap);
            }

            @Override
            public void accept(Bitmap bitmap) {
                dismissDialog();
                if (bitmap != null) {
                    mImgEditActivity.changeMainBitmap(bitmap, true);
                }
                mPaintView.reset();
                backToMain();
            }
        });

    }

    private void setMosaicBitmap(String path) {
        RxUtil.create(new RxUtil.Callback<Bitmap>() {
            @Override
            public void doBackground(ObservableEmitter<Bitmap> emitter) {
                Bitmap bitmap = null;
                try {
                    bitmap = Glide.with(mContext).asBitmap().load(path).submit().get();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                emitter.onNext(bitmap);
            }

            @Override
            public void accept(Bitmap bitmap) {
                if (bitmap != null) {
                    mPaintView.setMosaicBitmap(bitmap);
                }
            }
        });
    }

}